package com.tgjorgoski.window;

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;

import com.tgjorgoski.utils.*;

public class SearchPanel extends JToolBar implements DocumentListener, FocusListener, KeyListener {
	HTMLView htmlView;
	CalmRunner calmRunner;
	final static String writeSearchHere = "Write your search here"; 
	Color noHitsColor = new Color(240,240,200);
	JTextComponent tComp = new JTextField(20) {
		public void paint(Graphics g) {
			super.paint(g);
			if (!tComp.isFocusOwner() && tComp.getText().equals("")) {
				Graphics2D g2d = (Graphics2D)g;
				Color oldC = g2d.getColor();
				g2d.setColor(Color.LIGHT_GRAY);
				g2d.drawString(writeSearchHere, 5, 15);
				g2d.setColor(oldC);
			}
		}
	};
	Color defaultColor = tComp.getBackground();
	
	public SearchPanel(HTMLView htmlView) {
		//FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
		//setLayout(fl);
		setFloatable(false);
		setRollover(true);
		
		this.htmlView=htmlView;
		init();
	}
	
	private void init() {
		//FIXME:Change with icon to save space
		//JLabel sLabel = new JLabel("Search:");
		//sLabel.setIcon(IconResource.getIconResource("find"));
		SidekickNotesButton cc = new SidekickNotesButton();
		Dimension dd = cc.getPreferredSize();
		cc.setPreferredSize(dd);
		cc.addToToolBar(this);
		Component glue = Box.createHorizontalGlue();
		add(glue);
		//add(sLabel);
		FontMetrics fm = tComp.getFontMetrics(tComp.getFont());
		int height = fm.getHeight() + 8;
		int width = fm.stringWidth(writeSearchHere)+20;
		Dimension pSize = new Dimension(width, height);
		tComp.setMaximumSize(pSize);
		
		add(tComp);
		JLabel searchIcon = new JLabel(IconResource.getIconResource("find")); 
		add(searchIcon);
		tComp.getDocument().addDocumentListener(this);
		tComp.addFocusListener(this);
		tComp.addKeyListener(this);
		
		tComp.addFocusListener(this);
		
		// Install shortcut
		Action focusAction = new AbstractAction("focusOnSearch") {
			public void actionPerformed(ActionEvent e) {
				tComp.requestFocusInWindow();
			}
		};
		String name = (String) focusAction.getValue(Action.NAME);
		tComp.getActionMap().put(name, focusAction);
		InputMap inputMap = tComp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
		KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0);
		inputMap.put(key, name);
		
		invalidate();
		repaint();
	}
	
	public void updateTheSearch() {
		if (calmRunner==null) {
			calmRunner = new CalmRunner(new Runnable() {
				public void run() {
					String text = tComp.getText();
					int howMuch = htmlView.doSearch(text);
					if (!("".equals(text.trim())) && howMuch==0) {
						tComp.setBackground(noHitsColor);
						//Toolkit.getDefaultToolkit().beep();
					} else {
						tComp.setBackground(defaultColor);
					}
				}
			}, 500);
		}
		calmRunner.run();
	}
	
	public void clearTheSearch() {
		tComp.setText("");
	}

	public void changedUpdate(DocumentEvent e) {
		updateTheSearch();
	}

	public void insertUpdate(DocumentEvent e) {
		updateTheSearch();
	}

	public void removeUpdate(DocumentEvent e) {
		updateTheSearch();
	}
	
	public void focusGained(FocusEvent e) {
		tComp.repaint();
		tComp.setSelectionStart(0);
		tComp.setSelectionEnd(tComp.getText().length());
	}

	public void focusLost(FocusEvent e) {
		tComp.repaint();
	}

	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode()==KeyEvent.VK_ESCAPE) {
			htmlView.setFocusOnEditor();
		}
		if (e.getKeyCode()==KeyEvent.VK_DOWN || e.getKeyCode()==KeyEvent.VK_UP) {
			htmlView.setFocusOnBrowser();
		}
	}
	public void keyReleased(KeyEvent e) {
	}
	public void keyTyped(KeyEvent e) {
	}
	
	class SidekickNotesButton extends DropDownButton {
		JPopupMenu popupMenu;
		
		public SidekickNotesButton() {
			popupMenu = ViewUtils.createAndTrackPopupMenu();
			Action exit = new AbstractAction("Exit", IconResource.getIconResource("dialog-close")) {
				public void actionPerformed(ActionEvent e) {
					htmlView.exit();
				}
			};
			final JCheckBoxMenuItem spellCheckByDefault = new JCheckBoxMenuItem();
			spellCheckByDefault.setSelected(Session.isSpellcheckByDefaultOn());
			spellCheckByDefault.setText("Spellcheck On By Default");
			Session.addPropertyChangeListener(new PropertyChangeListener() {
				@Override
				public void propertyChange(PropertyChangeEvent evt) {
					if (evt.getPropertyName().equals(Session.PREF_SPELLCHECK)) {
						boolean newValue = (Boolean)evt.getNewValue();
						if (spellCheckByDefault.isSelected()!=newValue)
							spellCheckByDefault.setSelected(newValue);
					}
				}
			});
			spellCheckByDefault.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					boolean selected = spellCheckByDefault.isSelected();
					Session.setSpellecheck(selected);
				}
			});
			popupMenu.add(spellCheckByDefault);
			popupMenu.addSeparator();
			popupMenu.add(exit);
			setIcon(IconResource.getIconResource("sidekicknotes"));
			//popupMenu.addPopupMenuListener(this);
		}
		
		protected JPopupMenu getPopupMenu() {
	    	return popupMenu;
	    }
	}
}
